浏览器点击下载文件时,后端重命名文件名

前言

上传文件时,文件服务器会给文件重新生成一个一串英文字符的名称,导致前端使用a标签下载这个文件时,文件内容是原来的内容,但是下载的文件名是一串英文字符,很不好的用户体验。而且download也不是太好用
比如:上传的是原文件名是 "组织架构2019.pdf"
 

<a href="http://url/16/B9/rBADs1ytTmCASKrBAAL7byPiPRU439.pdf" download="组织架构2019.pdf" target="_blank">下载</a>

给下载的文件重命名


废话不多说上代码

    /**
	 *
	 * @param request
	 * @param fileUrl  下载路径
	 * @param fileName  文件名
	 * @param response
	 * @throws Exception
	 */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
	public void downloadAction(HttpServletRequest request, String fileUrl,String fileName,HttpServletResponse response) throws Exception {
		if (StringUtils.isBlank(fileUrl)) {
			throw new Exception("文件fileUrl为空");
		}
		if (StringUtils.isBlank(fileName)) {
			throw new Exception("文件fileName为空");
		}
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String downloadName = null;
		if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            //println "IE浏览器"
			downloadName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
			response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
		} else {
            //println "其他浏览器"
			downloadName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");//其他浏览器
			response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
		}
		URL url = new URL(fileUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置超时间为3秒
		conn.setConnectTimeout(3 * 10000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		//得到输入流
		InputStream inputStream = conn.getInputStream();
		OutputStream os = response.getOutputStream();
		try {
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			os.close();
			inputStream.close();
			conn.disconnect();
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值